package com.cn.system.login.action;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.cn.system.common.service.CommonService;
import com.cn.system.login.model.User;
import com.cn.system.login.service.UserService;

@Controller
public class LoginAction {

	@Resource
	private CommonService commonService;

	@RequestMapping("/loginPage")
	String login() {
		return "login";
	}

	@RequestMapping("/into-index")
	@ResponseBody
	public Map<String, Object> index() {
		// Map map = userService.queryUserForMap();
		return null;
	}

	@PostMapping("login")
	public String login(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession(true);
		String accounts = request.getParameter("username");
		String password = request.getParameter("password");
		Map user = commonService.findByAccounts(accounts);
		if (user != null) {
			if (user.get("PASSWORD").equals(password)) {
				session.setAttribute("user", user);
				request.setAttribute("user", user);
				return "index";
			} else {
				model.addAttribute("errMsg", "账号或密码错误");
			}
		} else {
			model.addAttribute("errMsg", "账号或密码错误");
		}
		return "login";
	}
	
	@RequestMapping(value ="/loginOut")
	public ModelAndView loginOut(HttpServletRequest request, ModelAndView mv,SessionStatus sessionStatus) {
		request.getSession(true).invalidate();
		sessionStatus.setComplete();
		mv.setViewName("login");
		return mv;
	}


	@RequestMapping("/add")
	String add() {
		User user = new User();
		user.setAccounts("aa");
		user.setPassword("1111");
		user.setName("测试");
		commonService.save(user);
		return "login";
	}

}
